package smcrypto

import (
	"github.com/ethereum/go-ethereum/sm2"
	"math/big"
)


func GetPublicKey(priv *sm2.PrivateKey) sm2.PublicKey {
	return  *sm2.CalculatePubKey(priv)
}

// Serialize returns the private key number d as a big-endian binary-encoded
// number, padded to a length of 32 bytes.
// paddedAppend appends the src byte slice to dst, returning the new slice.
// If the length of the source is smaller than the passed size, leading zero
// bytes are appended to the dst slice before appending src.
func paddedAppend(size uint, dst, src []byte) []byte {
	for i := 0; i < int(size)-len(src); i++ {
		dst = append(dst, 0)
	}
	return append(dst, src...)
}

const PrivKeyBytesLen = 32

func Serialize(priv *sm2.PrivateKey) []byte {
	b := make([]byte, 0, PrivKeyBytesLen)
	return paddedAppend(PrivKeyBytesLen, b, priv.D.Bytes())
}

// PrivKeyFromBytes returns a private and public key for `curve' based on the
// private key passed as an argument as a byte slice.
func PrivKeyFromBytes(curve sm2.P256V1Curve, pk []byte) *sm2.PrivateKey {
	priv := &sm2.PrivateKey{
		D:     new(big.Int).SetBytes(pk),
		Curve: curve,
	}
	return priv
}

// 加密
func Decrypt(priv *sm2.PrivateKey, hash []byte) ([]byte, error) {
	data, err := sm2.Decrypt(priv, hash, sm2.C1C3C2)
	if err != nil {
		return nil, err
	}
	return data, nil
}

// 签名
func SignToSign(priv *sm2.PrivateKey, data []byte) (*Signature, error) {
	r, s, v, err := sm2.SignToRSV(priv, nil, data)
	if err != nil {
		return nil, err
	}
	return &Signature{r, s, v}, nil
}

// 签名字节
func SignToData(priv *sm2.PrivateKey, data []byte) ([]byte, error) {
	r, s, v, err := sm2.SignToRSV(priv, nil, data)
	if err != nil {
		return nil, err
	}
	return SignSerialize(r, s, v)
}


